import React from 'react'
import { Button, Table, Modal, Form, Input, Select, message, Popconfirm, TreeSelect } from 'antd';
import './NewType.scss';
import { getTypeList, deleteType, addType, editType, getModalList } from '../../../services/typeFetch';
import {connect} from "dva";

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
@connect(({ type }) => ({
    type,
}))
class NewType extends React.PureComponent{

    state = {
        visible: false,
        visible2: false,
        class_id: ''
    };

    componentDidMount(){
        this.getList()
    }
    /**
     * 弹出模态框 新增  和 修改
     */
    showModal = () => {
        this.setState({
            visible: true
        })
    }
    showModalEdit = (edit)=>{
        this.formRef2.props.form.setFieldsValue({
            class_name: edit.class_name,
            pid:edit.pid
        });
        this.setState({
            visible2: true,
            class_id: edit.class_id
        })
    }
    /**
     * 新建分类
     */
    handleCreateAdd = (e) => {
        e.preventDefault();
        this.formRef.props.form.validateFieldsAndScroll((err, values) => {
            console.log(values)
        if (!err) {
            this.props.dispatch({ type: 'type/addInfoclass',payload:values});
            this.setState({
                visible: false
            })
            this.formRef.props.form.resetFields()
        }
        });
        
    }
    /**
     * 修改分类
     */
    handleCreateEdit = (e) => {
        e.preventDefault();
        this.formRef2.props.form.validateFieldsAndScroll((err, values) => {
            console.log(values)
            if (!err) {
                values["class_id"] = this.state.class_id
                this.props.dispatch({ type: 'type/updateInfoclass',payload:values});
                this.setState({
                    visible2: false
                })
            }
        })
    }
    //modal 控制
    handleCancel = (e) => {
        this.formRef.props.form.resetFields()
        this.setState({
            visible: false
        });
    }
    handleCancelEdit = (e) => {
        this.setState({
            visible2: false
        });
    }
    /**
     * 获取分类 数据
     */
    getList=()=>{
        this.props.dispatch({ type: 'type/classList'});
    }


    /**
     * 删除单个 分类
     */
    delete=(record)=>{
        let id = {
            class_id:record.class_id,
            pid:record.pid
        }
        this.props.dispatch({ type: 'type/deleteInfoclass',payload:id});
    }
    saveFormRef = (formRef) => {
        this.formRef = formRef;
    }
    saveFormRef2 = (formRef) => {
        this.formRef2 = formRef;
    }
    render() {
        const { classList } = this.props.type
        console.log(classList)
        const columns = [{
            title: '分类名称',
            className: 'mon_text',
            dataIndex: 'class_name',
            key:'class_name'
          }, {
            title: '创建时间',
            dataIndex: 'create_time',
            key:'create_time'
          },
          {
            title: '文章数量',
            dataIndex: 'info_total',
            key:'info_total'
          },{
            title: '操作',
            render:(text,record,index)=>{

                return(
                   <div>
                        <a style={{marginRight:'10px'}} onClick={()=>this.showModalEdit(record)}>修改</a>
                        <Popconfirm title="确定删除?" icon={null} onConfirm={()=>this.delete(record)} okText="确定" cancelText="取消">
                            <a >删除</a>
                        </Popconfirm>
                   </div>
                )
            }
          }];
        return (
            <section id='type' style={{width:'100%',height:'100%', padding: '10px'}}>
                <header>
                    分类管理
                </header>
                <div className='content new_types_content'>
                    <div className='btn_group'>
                        <Button className='mon_btn' type="defualt" onClick={this.showModal}>ᠠᠩᠬᠢᠯᠡᠯ ᠨᠡᠮᠡᠬᠦ</Button>
                    </div>
                    <div className='table_box'>
                        <Table 
                            className='mon_table'
                            columns={columns} 
                            dataSource={classList} 
                            pagination={false}
                            rowKey='class_id'
                            // pagination={{
                            //    style:{display:'none'}
                            //   }}
                        />
                    </div>
                </div>
                {/* modal */}
                    <AddForm
                        wrappedComponentRef={this.saveFormRef}
                        visible={this.state.visible}
                        onCancel={this.handleCancel}
                        onCreate={this.handleCreateAdd}
                        classList={classList}
                    />
                    <EditForm
                        wrappedComponentRef={this.saveFormRef2}
                        visible={this.state.visible2}
                        onCancel={this.handleCancelEdit}
                        onCreate={this.handleCreateEdit}
                    />
            </section>
        )
    }
}

export default NewType;


const EditForm = Form.create()(
    class extends React.Component {
        render(){
            const { visible, onCancel, onCreate, form } = this.props;
            const { getFieldDecorator } = form;
            const formItemLayout = {
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 5 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 },
                },
              };
            return(
                <Modal
                    title="修改"
                    visible={visible}
                    onCancel={onCancel}
                    onOk={onCreate}
                    footer={[
                        <Button className='mon_btn' onClick={onCancel}>ᠬᠠᠭᠠᠬᠤ</Button>,
                        <Button className='mon_btn' type="primary" onClick={onCreate}>ᠵᠠᠰᠠᠬᠤ</Button>
                    ]}
                >
                <Form >
                    <FormItem style={{display:'none'}} 
                        {...formItemLayout}
                        label="层级"
                    >
                        {getFieldDecorator('pid')(
                        <Input />
    )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        mon_class='mon_label'
                        mon_block=''
                        label="ᠠᠩᠭᠢᠯᠠᠯ᠎ᠤᠨ ᠨᠡᠷ᠎ᠡ : "
                    >
                        {getFieldDecorator('class_name', {
                            rules: [{
                            required: true, message: '',
                            }],
                        })(
                            <Input mon_class='mon_input' />
                        )}
                    </FormItem>
                   
                </Form>
                </Modal>
            )
        }
    })


    const AddForm = Form.create()(
        class extends React.Component {

            state = {
                currentValue:'0'
            };

            onChange = (value) => {
                console.log(value)
                this.setState({
                    currentValue:value
                })
            }
            setName = (datas) => { //遍历树  获取id数组
               datas.forEach((item,index) => {
                   item.key = item.class_id
                   item.title = item.class_name
                   item.value = item.class_id 
                   if(item.children&&item.children !== []){
                    this.setName(item.children);
                    }
               })
               
           }

            render(){
                const { visible, onCancel, onCreate, form,classList } = this.props;
                
                let treeData = JSON.parse(JSON.stringify(classList))

                let obj = {
                    class_id:'0',
                    class_name:'第一层'
                }
                treeData.unshift(obj)
                this.setName(treeData)
                console.log(treeData)
                const { getFieldDecorator } = form;
                const formItemLayout = {
                    labelCol: {
                        xs: { span: 24 },
                        sm: { span: 5 },
                    },
                    wrapperCol: {
                        xs: { span: 24 },
                        sm: { span: 16 },
                    },
                  };
                return(
                    <Modal
                        title='新建分类'
                        visible={visible}
                        onCancel={onCancel}
                        onOk={onCreate}
                        footer={[
                            <Button className='mon_btn' onClick={onCancel}>ᠬᠠᠭᠠᠬᠤ</Button>,
                            <Button className='mon_btn' type="primary" onClick={onCreate}>ᠨᠡᠮᠡᠬᠦ</Button>
                        ]}
                    >
                    <Form>
                    <FormItem
                        mon_class='mon_label'
                        mon_display='inline'
                        {...formItemLayout}
                        label="ᠳᠠᠪᠬᠤᠷᠭ᠎ᠠ : "
                        >
                            <div mon_class='mon_tree_select'>
                                {getFieldDecorator('pid', {
                                    initialValue:'0',
                                    rules: [{
                                    required: true, message: '请选择分类所在层级',
                                    }],
                                })(
                                    
                                    <TreeSelect
                                        //  style={{ width: 300, margin: '10px' }}
                                        dropdownStyle={{ maxHeight: 200 }}
                                        dropdownMatchSelectWidth
                                        placeholder="请选择分类"
                                        allowClear
                                        treeData={treeData}
                                        //  treeDefaultExpandAll
                                        onChange={this.onChange}
                                    >
                                    </TreeSelect>
                                )}
                            </div>
                        </FormItem>
                        <FormItem
                            mon_class='mon_label'
                            mon_display='inline'
                            {...formItemLayout}
                            label="ᠠᠩᠭᠢᠯᠠᠯ᠎ᠤᠨ ᠨᠡᠷ᠎ᠡ : "
                            >
                            {getFieldDecorator('class_name', {
                                rules: [{
                                required: true, message: '请输入分类名称',
                                }],
                            })(
                                <Input mon_class='mon_input' />
                            )}
                            </FormItem>
                        
                        </Form>
                    </Modal>
                )
            }
        })